package com.eonmind.pay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.eonmind.common.contract.data.response.ResponseEntity;
import com.eonmind.common.provider.entity.pay.Cart;
import com.eonmind.common.provider.entity.pay.Order;
import com.eonmind.common.provider.entity.vip.VipPackage;
import com.eonmind.pay.PayApplication;
import com.eonmind.pay.dto.OrderDto;
import com.eonmind.pay.enums.TradeState;
import com.eonmind.pay.mapper.CartMapper;
import com.eonmind.pay.mapper.OrderMapper;
import com.eonmind.pay.service.OrderService;
import com.mongoplus.conditions.update.UpdateChainWrapper;
import com.mongoplus.model.PageResult;
import com.mongoplus.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName OrderServiceImpl
 * @Description TODO
 * Author 32004
 * Date 2025/5/5 14:13
 * Version 1.0
 **/

@Service
public class OrderServiceImpl extends ServiceImpl<Order> implements OrderService {


    @Resource
    CartMapper cartMapper;

    @Resource
    OrderMapper orderMapper;


    @Override
    public Order findSameNoPayOrder(Integer type, Long userId,double amount,List<Cart> carts) {
        //1.查询未支付且未过期订单
        List<Order> noPayOrderList=orderMapper.selectNoPayOrder(userId,type);
        if(noPayOrderList.isEmpty()){
            return null;
        }

        //2.查询每个订单关联的购物车商品是否与当前购物车商品一致
        for(Order order:noPayOrderList){
            //金额一致
            if(order.getAmount()==amount){
                List<Cart> cartsPre=cartMapper.selectListByOrderId(order.getId());
                HashMap<Long,Integer> countMap=new HashMap<>();
                //商品种类数一致
                if(cartsPre.size()==carts.size()){
                    cartsPre.forEach(cart->{
                        countMap.put(cart.getProductId(),cart.getCount());
                    });
                    boolean flag=true;
                    //比对各商品和数量
                    for(Cart cart:carts){
                        if(!countMap.containsKey(cart.getProductId())||
                                !countMap.get(cart.getProductId()).equals(cart.getCount())){
                            flag=false;
                            break;
                        }
                    }
                    if(flag){
                        return order;
                    }
                }
            }
        }
        return null;
    }


    @Override
    public Boolean getPayStatus(Long orderId) {
        Order order = this.getById(orderId);

        if(order==null||order.getStatus()!=TradeState.SUCCESS.getCode()){
            return false;
        }else{
            System.out.println(order);
            return true;
        }
    }

    @Override
    public void updateOrderStatusAndPayTime(long orderNo, Integer code, long payTime) {
        orderMapper.updateOrderStatusAndPayTime(orderNo,code,payTime);

    }

    @Override
    public ResponseEntity<OrderDto> pageOrder(Long userId, OrderDto.OrderPageRequest pageRequest) {
        List<Long> orderIds=new ArrayList<>();
        if(StringUtils.hasText(pageRequest.getProductName())){
            System.out.println("商品名称："+pageRequest.getProductName());
            //TODO 调用远程服务获取商品的ID
//            Long productId=1L;
//
            List<Long> productsId=new ArrayList<>();
            for(Long id:PayApplication.vipMap.keySet()){
                if(PayApplication.vipMap.get(id).getName().contains(pageRequest.getProductName())){
                    productsId.add(id);
                }
            }
            productsId.forEach(id->{
                List<Long> orderList = cartMapper.selectCartByProductId(id, userId).stream().map(Cart::getOrderId).toList();
                orderIds.addAll(orderList);
            });
        }
        System.out.println("订单ID："+orderIds);

        //TODO 调用远程服务获取商品列表信息，此处仅为测试数据


        PageResult<Order> orderPageResult = orderMapper.pageOrder(userId, pageRequest, orderIds);
        OrderDto orderDto = new OrderDto();
        BeanUtil.copyProperties(orderPageResult, orderDto);
        List<OrderDto.OrderResDto> dataList = orderPageResult.getContentData().stream().map(item -> {
            OrderDto.OrderResDto orderResDto = new OrderDto.OrderResDto();
            List<Cart> carts = cartMapper.selectListByOrderId(item.getId());
            //订单中的商品列表
            List<OrderDto.OrderDetailDto> detailDtoList = carts.stream().map(cart -> {
                OrderDto.OrderDetailDto detailDto = new OrderDto.OrderDetailDto();
                detailDto.setMenu(PayApplication.vipMap.get(cart.getProductId()));
                detailDto.setCount(cart.getCount());
                return detailDto;
            }).toList();
            orderResDto.setGoodsList(detailDtoList);
            orderResDto.setOrder(item);
            orderResDto.setOrderNo(item.getId().toString());
            return orderResDto;
        }).toList();

        orderDto.setOrderList(dataList);
        return ResponseEntity.success("获取订单分页成功！",orderDto);
    }

    @Override
    public List<Order> getNoPayByDuration(int minute) {
        return orderMapper.selectNoPayOrderByDuration(minute*60*1000);
    }

    @Override
    public ResponseEntity<OrderDto.OrderResDto> getOrderById(Long id) {
        Order order = orderMapper.getById(id);
        orderMapper.setUpdateTime(order);
        OrderDto.OrderResDto orderResDto = new OrderDto.OrderResDto();
        orderResDto.setOrder(order);
        orderResDto.setOrderNo(order.getId().toString());
        return ResponseEntity.success("获取订单成功！",orderResDto);
    }

    @Override
    public ResponseEntity<List<OrderDto.OrderResDto>> getRecentOrder(Long id) {
        List<Order> list=orderMapper.getRecentOrder(id);
        List<OrderDto.OrderResDto> res=new ArrayList<>();
        for(int i=0;i<list.size()&&i<7;i++){
            OrderDto.OrderResDto orderResDto = new OrderDto.OrderResDto();
            orderResDto.setOrder(list.get(i));
            orderResDto.setOrderNo(list.get(i).getId().toString());
            res.add(orderResDto);
        }
        return ResponseEntity.success("获取最近订单成功！",res);
    }

    @Override
    public ResponseEntity<Boolean> deleteOrder(Order order) {
        orderMapper.removeById(order.getId());
        return ResponseEntity.success("删除订单成功！",true);
    }


}
